package cn.cvs.service.comment;

import cn.cvs.dao.comment.CommentMapper;
import cn.cvs.dao.sysUser.SysUserMapper;
import cn.cvs.dao.user.UserMapper;
import cn.cvs.pojo.Comment;
import cn.cvs.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentDao;

    @Autowired
    private UserMapper userDao;//

    @Override
    public void addComment(Comment comment) {
        commentDao.addComment(comment);
    }

    public List<Comment> getCommentsByPetId(Integer petId) {
        List<Comment> topLevelComments = commentDao.getCommentsByPetId(petId);
        for (Comment comment : topLevelComments) {
            User user = userDao.selectById(comment.getUserId());
            comment.setUser(user);
            findReplies(comment);
        }
        return topLevelComments;
    }

    private void findReplies(Comment comment) {
        Integer commentId = comment.getId();
        List<Comment> replies = commentDao.getCommentsByParentId(commentId);
        for (Comment reply : replies) {
            User user = userDao.selectById(reply.getUserId());
            reply.setUser(user);
                comment.getReplies().add(reply);
                findReplies(reply);

        }
    }

    @Override
    public void deleteComment(Integer commentId) {
        commentDao.deleteComment(commentId);
    }

    @Override
    public List<Comment> list(Integer state, Integer pageIndex, Integer pageSize) {
        int pageBean = (pageIndex - 1) * pageSize;
        return commentDao.list(state, pageBean, pageSize);
    }

    @Override
    public int count(Integer state) {
        return commentDao.count(state);
    }

    @Override
    public int update(Comment comment) {
        return commentDao.update(comment);
    }

    @Override
    public Comment getById(Integer commentId) {
        return commentDao.getById(commentId);
    }
}